import _ from 'lodash';
import { message } from 'antd';
import { routerRedux } from 'dva/router';
import { matchDict } from '@/utils/utils';
import {
  getEmpList,
  probEmpList,
  empTabNum,
  cancelAdjust,
  getProDetail,
  getFeedback,
  getEmpNameList,
  getAdjInsDetail,
  fetchAdjInsDetail,
  getAdjInsUpdateDetail,
  getInsIdeList,
  getSerConfigList,
  getAcountList,
  getInsGroupList,
  getSecAccoList,
  insSubmit,
  updateInsSubmit,
  getRespUserList,
} from '@/services/adjusttask';

export default {
  state: {
    data: {
      // 列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    tabList: [
      { itemCode: '1', itemName: '办理中', isHas: false },
      { itemCode: '2', itemName: '已完成', isHas: false },
      { itemCode: '4', itemName: '问题人员', isHas: false },
    ],
    proBaseList: {},
    proFbList: [],
    probId: '',
    empNameList: [], // 单个调整雇员姓名
    // 调整信息
    updateBaseInfo: {}, // 基本信息
    updateInsIde: null, // 缴费人员类别
    updateInsLocPkgList: null, // 社保组合
    updateInsPdDecWage: null, // 社保申报工资
    insIdeFlag: false, // 是否修改缴费人员类别
    insIdeList: [], // 缴费人员类别列表
    insWageFlag: false, // 是否修改社保申报工资
    insSetFlag: 1, // 五险合不合一
    isAssSetFlag: '', // 社保工资分项:1是2否
    insLocFlag: false, // 是否修改社保组合
    insSerConfigFlag: '2', // 社保组合是否使用服务配置
    serConfigList: [], // 服务配置列表
    insPayWayList: [], // 社保缴费方式
    accountList: [], // 缴费账户列表
    insGroupList: [], // 社保组合列表
    isHasSerAcco: false, // 有无工伤险种,
    secAccoList: [], // 工伤二级户列表
    insGroupData: [], // 社保组合数据
    insList: [], // 险种集合
    payWay: null, // 缴费方式：1单立户  2大库
    isHasSingle: false, // 有无单立户
    isHasbigStore: false, // 有无大库
    sendId: null,
    beginDate: undefined,
    activeKey: '1',
    formFieldsValue: {},
    valuesArr: [
      'empName',
      'idCode',
      'custId',
      'custContId',
      'sendCorp',
      'quoId',
      'operTime',
      'primId',
    ],
    expandForm: false,
    isSupplyRun: false,
    respUserList: [],
    downloadParams: {}, // 问题人员导出参数
  },
  effects: {
    // 获取列表
    fetchList: [
      function*({ payload }, { call, put }) {
        const response = yield call(getEmpList, payload);
        const {
          pageArg: { currentPage, pageSize },
        } = payload;
        if (response.success) {
          yield put({
            type: 'getList',
            payload: {
              data: response.data,
              currentPage,
              pageSize,
            },
          });
        } else {
          yield put({
            type: 'getList',
            payload: {
              data: [],
              currentPage,
              pageSize,
            },
          });
          message.warning(`${response.message || '服务端错误！'}`);
        }
      },
      { type: 'takeLatest' },
    ],
    // 获取问题人员列表
    *fetchProbList({ payload }, { call, put }) {
      const response = yield call(probEmpList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        yield put({
          type: 'getList',
          payload: {
            data: [],
            currentPage,
            pageSize,
          },
        });
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    /**
     * 获取页签数量
     * @param {action} action
     * @param {effects} effects
     * @return {response} response
     */
    *fetchTabNum({ payload }, { call }) {
      const temp = payload;
      temp.formFieldsValue.adjStatus = payload.adjStatus;
      const response = yield call(empTabNum, payload.formFieldsValue);
      return response;
    },
    /**
     * 设置激活页签
     * @param {action} action
     * @param {effects} effects
     * @return {string} activeKey
     */
    *setFetchTabNumActiveKey({ payload }, { put, select }) {
      let activeKey = yield select(state => state.adjusttask.activeKey);
      const newTabList = yield select(state => state.adjusttask.tabList);
      const tabList = _.cloneDeep(newTabList);
      const { data } = payload;
      // 按itemCode大小排序
      const sortNumber = (a, b) => a.itemCode - b.itemCode;
      // 排序后的tabCode数组
      const tabCodeArr = data.sort(sortNumber);
      // 在tabCodeArr中找到当前的激活项
      const isHasBadgeCurrentTab = tabCodeArr.some(item => `${item.sendOper}` === activeKey); // 当前页签有没有查询到
      // 没有找到就把第0项设为当前的激活项
      if (!isHasBadgeCurrentTab) {
        activeKey = `${tabCodeArr[0].sendOper}`;
      }

      tabCodeArr.forEach(item => {
        if (`${item.sendOper}` !== activeKey) {
          if (item.sendOper === 4) {
            tabList[item.sendOper - 2].isHasBadge = true;
          } else {
            tabList[item.sendOper - 1].isHasBadge = true;
          }
        }
      });
      yield put({
        type: 'updateModelData',
        payload: { activeKey, tabList },
      });
      return activeKey;
    },
    *setFetchTabNumFormFieldsValue({ payload }, { put, select }) {
      const activeKey = yield select(state => state.adjusttask.activeKey);
      const getListParams = {
        ...payload.formFieldsValue,
        pageArg: { currentPage: payload.currentPage, pageSize: payload.pageSize },
      };

      if (activeKey === '4') {
        if (payload.formFieldsValue) {
          yield put({
            type: 'updateModelData',
            payload: {
              ...payload.formFieldsValue,
            },
          });
        }
        yield put({
          type: 'problempage/getProList',
          payload: {
            ...getListParams,
            busiType: 22,
          },
        });
      } else {
        yield put({
          type: 'fetchList',
          payload: { ...getListParams, adjStatus: activeKey },
        });
      }
    },
    *setFetchTabNumNoResult(action, { put, select }) {
      const activeKey = yield select(state => state.adjusttask.activeKey);
      yield put({
        type: 'getList',
        payload: {
          data: {},
          currentPage: 1,
          pageSize: 10,
        },
      });
      if (activeKey === '4') {
        yield put({
          type: 'problempage/updateProList',
          payload: {
            data: [],
            currentPage: 1,
            pageSize: 10,
          },
        });
      }
    },
    // 取消调整
    *cancelAdjust({ payload, callback }, { call }) {
      const response = yield call(cancelAdjust, payload);
      if (callback) callback(response);
    },
    // 获取问题人员详情
    *fetchProDetailList({ payload }, { call, put }) {
      const response = yield call(getProDetail, payload);
      if (response.success) {
        yield put({
          type: 'getProDetail',
          payload: response.data,
        });
      }
    },
    // 问题人员反馈
    *proFeedBack({ payload, callback }, { call }) {
      const response = yield call(getFeedback, payload);
      if (response.success) {
        if (callback) {
          callback(response);
        }
      } else {
        message.warning(`${response.message || '反馈失败'}`);
      }
    },
    // 问题人员反馈并取消标记
    *cancelProbFlag({ payload, callback }, { call }) {
      const response = yield call(getFeedback, payload);
      if (callback) {
        callback(response);
      }
    },
    // 单个调整：输入姓名,证件号模糊查询
    // eslint-disable-next-line consistent-return
    *fetchEmpNameList({ payload }, { call, put }) {
      const response = yield call(getEmpNameList, payload);
      if (response.success) {
        yield put({
          type: 'getEmpNameList',
          payload: response.data,
        });
        return response.data;
      }
    },
    // 获取是否进去下一步
    *fetchNextStep({ payload }, { call }) {
      const response = yield call(getAdjInsDetail, payload);
      return response;
    },
    // 单个调整：获取社保信息
    *fetchAdjInsDetail({ payload }, { call, put, select }) {
      const response = yield call(
        payload.adjId ? getAdjInsUpdateDetail : fetchAdjInsDetail,
        payload
      );
      const dictCode = yield select(state => state.publicdata.dictCode);
      const insList = [];
      let isHasSingle = false;
      let isHasbigStore = false;
      let isHasSerAcco = false;
      if (response.success) {
        if (response.data.insPayWayList) {
          const newInsPayWayList = [];
          if (dictCode.PAY_FEES_WAY.length) {
            isHasSingle = response.data.insPayWayList.some(item => item === '1');
            isHasbigStore = response.data.insPayWayList.some(item => item === '2');
            response.data.insPayWayList.forEach(l => {
              newInsPayWayList.push({
                itemCode: l,
                itemName: matchDict(dictCode.PAY_FEES_WAY, l),
              });
            });
          }
          response.data.insPayWayList = newInsPayWayList;
        }
        if (response.data.updateInsLocPkgList) {
          isHasSerAcco = response.data.updateInsLocPkgList.some(item => item.ass === 5);
          if (dictCode.PAY_FEES_WAY.length) {
            response.data.updateInsLocPkgList.forEach(item => {
              insList.push(item.ass);
            });
          }
        }
        if (payload.adjId) {
          // 获取缴费人员类别
          if (response.data.insIdeFlag) {
            yield put({
              type: 'fetchInsIdeList',
              payload: {
                areaId: response.data.updateBaseInfo.cityId,
              },
            });
          }
        }
        // 判断分项险种设置
        if (response.data.updateInsPdDecWage) {
          const data = response.data.updateInsPdDecWage;
          if (data.assSetFlag) {
            // 为true，默认为否
            yield put({
              type: 'updateModelData',
              payload: {
                isAssSetFlag: '2',
              },
            });
          } else {
            // 为false，默认为是
            yield put({
              type: 'updateModelData',
              payload: {
                isAssSetFlag: '1',
              },
            });
          }
        }
        yield put({
          type: 'updateModelData',
          payload: {
            ...payload,
            ...response.data,
            updateInsLocPkgListOld: _.cloneDeep(response.data.updateInsLocPkgList),
            insGroupData: _.cloneDeep(response.data.updateInsLocPkgList),
            insSetFlag: response.data.updateBaseInfo && response.data.updateBaseInfo.insSetFlag,
            sendId: response.data.updateBaseInfo && response.data.updateBaseInfo.sendId,
            custId: response.data.updateBaseInfo && response.data.updateBaseInfo.custId,
            insList,
            isHasSingle,
            isHasbigStore,
            isHasSerAcco,
            isSupplyRun:
              (response.data.updateBaseInfo && response.data.updateBaseInfo.execType === 2) ||
              false,
          },
        });
      } else {
        message.warning(response.message || '获取人员信息：服务端错误');
      }
    },

    // 获取缴费人员列表
    *fetchInsIdeList({ payload }, { call, put }) {
      const response = yield call(getInsIdeList, payload);
      if (response.success) {
        if (response.data) {
          yield put({
            type: 'updateModelData',
            payload: {
              insIdeList: response.data,
            },
          });
        } else {
          message.warning('该地区下未维护缴费人员');
        }
      } else {
        message.warning(response.message || '获取缴费人员列表：服务端错误');
      }
    },
    // 获取服务配置列表
    // eslint-disable-next-line no-shadow
    *fetchSerConfigList(_, { call, put, select }) {
      const adjustInfo = yield select(state => state.adjusttask);
      const { custId } = adjustInfo;
      const areaId = adjustInfo.updateBaseInfo.cityId;
      const kindList = [];
      adjustInfo.insList.forEach(item => {
        kindList.push({
          kind: item,
          areaId,
        });
      });
      const { quoId } = adjustInfo.updateBaseInfo;
      const response = yield call(getSerConfigList, { custId, kindList, quoId });
      if (response.success) {
        if (response.data && response.data.length) {
          yield put({
            type: 'updateModelData',
            payload: {
              serConfigList: response.data,
            },
          });
        } else {
          yield put({
            type: 'updateModelData',
            payload: {
              serConfigList: [],
            },
          });
          message.warning('该地区下未维护服务配置');
        }
      } else {
        message.warning(response.message || '获取服务配置列表：服务端错误');
      }
    },
    // 获取社保账户列表
    // eslint-disable-next-line consistent-return
    *fetchAcountList(
      {
        payload: { payWay },
      },
      { call, put, select }
    ) {
      const adjustInfo = yield select(state => state.adjusttask);
      const insKinds = adjustInfo.insSetFlag === 1 ? ['3', '4', '5', '6', '7'] : adjustInfo.insList;
      const areaId = adjustInfo.updateBaseInfo.cityId;
      const { custId } = adjustInfo;
      const response = yield call(getAcountList, { custId, insKinds, areaId, payWay });
      if (response.success) {
        if (response.data) {
          yield put({
            type: 'updateModelData',
            payload: {
              accountList: response.data,
            },
          });
          return response.data;
        }
        message.warning('该地区下未维护社保账户');
      } else {
        message.warning(response.message || '获取社保账户列表：服务端错误');
      }
    },

    // 获取社保组合列表
    // eslint-disable-next-line no-shadow
    *fetchInsGroupList(_, { call, put, select }) {
      const adjustInfo = yield select(state => state.adjusttask);
      const insKinds = adjustInfo.insSetFlag === 1 ? ['3', '4', '5', '6', '7'] : adjustInfo.insList;
      const areaId = adjustInfo.updateBaseInfo.cityId;
      const { custId } = adjustInfo;
      const response = yield call(getInsGroupList, {
        custId,
        areaId,
        pdId: 'PDINF_0000000001',
        insKinds,
      });
      if (response.success) {
        if (response.data) {
          yield put({
            type: 'updateModelData',
            payload: {
              insGroupList: response.data,
            },
          });
        } else {
          message.warning('该地区下未维护社保组合');
        }
      } else {
        message.warning(response.message || '获取社保组合列表：服务端错误');
      }
    },
    // 获取工伤二级户列表
    *fetchSecAccoList(
      {
        payload: { payWay },
      },
      { call, put, select }
    ) {
      const adjustInfo = yield select(state => state.adjusttask);
      const areaId = adjustInfo.updateBaseInfo.cityId;
      const { custId } = adjustInfo;
      const response = yield call(getSecAccoList, { custId, areaId, payWay, insKinds: ['5'] });
      if (response.success) {
        if (response.data) {
          // eslint-disable-next-line array-callback-return
          response.data.map(item => {
            // eslint-disable-next-line no-param-reassign
            item.value = item.accoId;
            // eslint-disable-next-line no-param-reassign
            item.label = item.accoName;
            // eslint-disable-next-line no-param-reassign
            item.isLeaf = (item.injSecAccoDtos && false) || true;
            if (item.injSecAccoDtos) {
              const children = [];
              // eslint-disable-next-line array-callback-return
              item.injSecAccoDtos.map(c => {
                children.push({
                  value: c.injSecAccoId,
                  label: c.injSecAccoName,
                  isLeaf: true,
                });
              });
              // eslint-disable-next-line no-param-reassign
              item.children = children;
            }
          });
          yield put({
            type: 'updateModelData',
            payload: {
              secAccoList: response.data,
            },
          });
        } else {
          message.warning('该地区下未维护社工伤二级户');
        }
      } else {
        message.warning(response.message || '获取工伤二级户列表：服务端错误');
      }
    },
    // 提交数据
    *submit({ payload }, { call, put, select }) {
      const updateInsDecWageList = [];
      const adjustInfo = yield select(state => state.adjusttask);
      const { sendId, insIdeFlag, insWageFlag, insLocFlag } = adjustInfo;
      let submitData = {
        sendId,
        insIdeFlag,
        insWageFlag,
        insLocFlag,
        updateInsIde: {},
        updateInsPdDecWage: {},
        adjLocPkgDto: {},
      };
      // eslint-disable-next-line no-param-reassign
      delete payload.values.insGroupTable;
      Object.entries(payload.values).forEach(([key, value]) => {
        if (key === 'beginDate') {
          submitData[key] = value && value.format('YYYY-MM-01');
        } else if (key === 'insIdeFlag' && value) {
          submitData.updateInsIde = payload.values.updateInsIde || '';
        } else if (key === 'insWageFlag' && value) {
          // 修改工资
          submitData.updateInsPdDecWage = payload.values.updateInsPdDecWage;
          if (adjustInfo.insSetFlag === 2) {
            // 五险不合一
            // eslint-disable-next-line no-unused-expressions
            adjustInfo.updateInsPdDecWage &&
              // eslint-disable-next-line array-callback-return
              adjustInfo.updateInsPdDecWage.updateInsDecWageList.map(item => {
                updateInsDecWageList.push({
                  ass: item.ass,
                  insDecWage:
                    adjustInfo.isAssSetFlag === '1'
                      ? payload.values.updateInsPdDecWage.updateInsDecWageList[`wage_${item.ass}`]
                      : payload.values.updateInsPdDecWage.insDecWage,
                });
              });
            submitData.updateInsPdDecWage.updateInsDecWageList = updateInsDecWageList;
          }
        } else if (key === 'insLocFlag' && value) {
          // 修改社保组合
          submitData.adjLocPkgDto = {
            accoId:
              (payload.values.accoId && payload.values.accoId.key) ||
              (payload.values.bigAccoId && payload.values.bigAccoId.key) ||
              '',
            grpId: (payload.values.grpId && payload.values.grpId.key) || '',
            payWay: (payload.values.payWay && payload.values.payWay.key) || '',
            serSetId:
              adjustInfo.insSerConfigFlag === '1'
                ? payload.values.serSetId && payload.values.serSetId.key
                : '',
            injAccoId:
              (payload.values.injAccoId &&
                payload.values.injAccoId[payload.values.injAccoId.length - 1]) ||
              '',
          };
        }
      });
      submitData = payload.adjId ? { ...submitData, adjId: payload.adjId } : submitData;
      const response = yield call(payload.adjId ? updateInsSubmit : insSubmit, submitData);
      if (response.success) {
        // message.success(payload.adjId ? '保存成功!' : '新增成功！');
        if (payload.adjId) {
          message.success('保存成功!');
        }

        yield put(
          routerRedux.push({
            pathname: payload.adjId
              ? '/customservicemanage/adjusttask/index'
              : '/customservicemanage/adjusttask/adjustfinish',
          })
        );
      } else {
        message.warning(`${response.message || '保存失败！'}`);
      }
    },
    // 获取所属客服列表
    *fetchRespUserList({ payload }, { call, put }) {
      const response = yield call(getRespUserList, payload);
      yield put({
        type: 'updateModelData',
        payload: {
          respUserList: [],
        },
      });
      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: {
            respUserList: Array.isArray(response.data) ? response.data : [],
          },
        });
      } else {
        message.warning(response.message || '获取所属客服数据：服务端错误');
      }
    },
  },

  reducers: {
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        data: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 问题人员详情
    getProDetail(state, { payload }) {
      return {
        ...state,
        proBaseList: payload,
        proFbList: payload.probFdbkList,
        probId: payload.probId,
      };
    },
    // 单个调整：雇员姓名
    getEmpNameList(state, { payload }) {
      return {
        ...state,
        empNameList: payload,
      };
    },
    // 设置页签状态
    updateTabListQuery(state, { payload }) {
      const { tabList } = state;
      tabList.forEach((item, index) => {
        if (item.itemCode === payload.activeKey) {
          tabList[index].isHasBadge = false;
        }
      });
      return {
        ...state,
        tabList,
        ...payload,
      };
    },
  },
};
